import React from "react";
import { Form, Input, Modal, Select, Switch } from "antd";
import { openNotificationWithIcon } from "utils/comm";
import Tags from "./Tags";

const { TextArea } = Input;
const { Option } = Select;

const formItemLayout1 = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 },
};

@Form.create()
class CreateForm extends React.Component {
  constructor(props) {
    super(props);
    this.openNotificationWithIcon = openNotificationWithIcon.bind(this);
    this.inputRef = React.createRef();
    this.textareaRef = React.createRef();

    this.state = {
      templateType: [], // 通知模板类型
      templateParam: [], // 通知模板参数
    };
  }

  componentDidMount() {
    const { data = {}, dispatch } = this.props;
    if (data.type) {
      dispatch({
        type: "noticeManagement/getTemplateParameter",
        payload: { type: data.type },
      }).then(({ errCode, datas }) => {
        if (errCode === 0) {
          this.setState({
            templateParam: datas,
          });
        }
      });
    }
    this.initStaticData();
  }

  initStaticData = () => {
    const { dispatch } = this.props;
    dispatch({ type: "noticeManagement/getTemplateType" }).then(
      ({ errCode, datas }) => {
        if (errCode === 0) {
          this.setState({
            templateType: datas,
          });
        }
      },
    );
  };

  handleChange = (value) => {
    const { dispatch, form } = this.props;
    dispatch({
      type: "noticeManagement/getTemplateParameter",
      payload: { type: value },
    }).then(({ errCode, datas }) => {
      if (errCode === 0) {
        this.setState({
          templateParam: datas,
        });
        form.resetFields(["title"]);
        form.resetFields(["content"]);
      }
    });
  };

  handleOk = (e) => {
    if (e && e.preventDefault) e.preventDefault();
    const { form, dispatch, data } = this.props;
    form.validateFields((err, values) => {
      if (err) {
        return;
      }

      let type = "noticeManagement/addNotice";
      if (data) type = "noticeManagement/editNotice";
      values.name = values.name && values.name.trim();
      values.title = values.title && values.title.trim();
      const record = data || {};
      if (values.type === record.typeName) {
        values.type = record.type;
      }
      dispatch({ type, payload: { ...record, ...values } }).then((resp) => {
        const { errCode, errortext } = resp;
        if (errCode === 0) {
          this.handleCancel(true);
          form.resetFields();
          this.openNotificationWithIcon("success", "", errortext || "操作成功");
        } else {
          this.openNotificationWithIcon("warning", "", errortext || "操作失败");
        }
      });
    });
  };

  handleCancel = (isQuery = false) => {
    const { handleCreateVisible } = this.props;
    handleCreateVisible(false, "", isQuery);
  };

  tagClick = (tag) => {
    const { form } = this.props;
    window.addEventListener("mousedown", (e) => {
      if (e.target.id === "param") e.preventDefault();
      if (e.target.id !== "param") this.focusPos = e.target.id;
    });
    const input = document.getElementById("title");
    const InputIndex = input.selectionStart;
    const textArea = document.getElementById("content");
    const textIndex = textArea.selectionStart;
    const inputValue = input.value || "";
    const textValue = textArea.value || "";
    if (this.focusPos === "title") {
      input.value = `${inputValue.slice(0, InputIndex)}${tag}${inputValue.slice(
        InputIndex,
        inputValue.length - 1,
      )}`;
      form.setFieldsValue({
        title: input.value,
      });
      form.validateFields(["title"]);
    }
    if (this.focusPos === "content") {
      textArea.value = `${textValue.slice(0, textIndex)}${tag}${textValue.slice(
        textIndex,
        textValue.length - 1,
      )}`;
      form.setFieldsValue({
        content: textArea.value,
      });
      form.validateFields(["content"]);
    }
  };

  render() {
    const { form, visible, confirmLoading, data = {}, title = "" } = this.props;
    const record = data || {};
    const { getFieldDecorator, getFieldValue } = form;
    const status = getFieldValue("status");
    const { templateType, templateParam } = this.state;
    return (
      <Modal
        title={title}
        visible={visible}
        onOk={this.handleOk}
        onCancel={() => this.handleCancel()}
        width="582px"
        centered
        confirmLoading={confirmLoading}
      >
        <Form>
          <Form.Item label="模板名称" {...formItemLayout1}>
            {getFieldDecorator("name", {
              initialValue: record.name || "",
              rules: [
                { required: true, message: "请输入模板名称" },
                { whitespace: true, message: "请输入模板名称" },
                { max: 20, message: "请不要超过20个字符" },
              ],
            })(<Input placeholder="请输入模板名称" />)}
          </Form.Item>
          <Form.Item label="模板类型" {...formItemLayout1}>
            {getFieldDecorator("type", {
              initialValue: record.typeName,
              rules: [{ required: true, message: "请选择模板类型" }],
            })(
              <Select placeholder="请选择" onChange={this.handleChange}>
                {Array.isArray(templateType) &&
                  templateType.map((item = {}) => (
                    <Option key={item.key} value={item.key}>
                      {item.value}
                    </Option>
                  ))}
              </Select>,
            )}
          </Form.Item>
          <Form.Item
            label="模板参数"
            {...formItemLayout1}
            style={{ marginBottom: 16 }}
            help="选择模版参数的时候，注意光标位置，支持标题和内容。"
          >
            {getFieldDecorator("param")(
              <Tags data={templateParam} tagClick={this.tagClick} />,
            )}
          </Form.Item>
          <Form.Item label="通知标题" {...formItemLayout1}>
            {getFieldDecorator("title", {
              initialValue: record.title || "",
              rules: [
                { max: 20, message: "请不要超过20个字符" },
                { required: true, message: "请输入通知标题" },
              ],
            })(
              <Input
                id="title"
                placeholder="请输入通知标题"
                onFocus={() => {
                  this.focusPos = "title";
                }}
              />,
            )}
          </Form.Item>
          <Form.Item label="通知内容" {...formItemLayout1}>
            {getFieldDecorator("content", {
              initialValue: record.content || "",
              rules: [
                { max: 100, message: "请不要超过100个字符" },
                { required: true, message: "请输入通知内容" },
              ],
            })(
              <TextArea
                id="content"
                placeholder="通知内容"
                rows={4}
                onFocus={() => {
                  this.focusPos = "content";
                }}
              />,
            )}
          </Form.Item>
          <Form.Item label="模板状态" {...formItemLayout1}>
            {getFieldDecorator("status", {
              initialValue: record.status || false,
              rules: [{ required: true, message: "" }],
            })(
              <Switch
                checked={Boolean(status)}
                // onChange={() => this.handleSwitchChange(status)}
              />,
            )}
          </Form.Item>
        </Form>
      </Modal>
    );
  }
}

export default CreateForm;
